package com.cqc.crm.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.cqc.crm.domain.User;
import com.cqc.crm.service.UserService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class UserAction extends ActionSupport implements ModelDriven<User> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5794153172697370615L;
	private User user = new User();

	@Override
	public User getModel() {
		return user;
	}

	private UserService userService;
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/**
	 * 判断用户名是否重复
	 * 
	 * @return
	 */
	public void checkUserName() {
		String user_name = user.getUser_name();
		List<User> list = userService.findUserByUserName(user_name);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			if (list != null && list.size() > 0) {
				writer.print("no");
			} else {
				// 没有重复的，可以使用
				writer.print("yes");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}

	/**
	 * 注册
	 * 
	 * @return
	 */
	public String regist() {
		userService.save(user);
		return LOGIN;
	}

	/**
	 * 登陆
	 * @return
	 */
	public String login() {
		List<User> list=userService.login(user);
		if(list!=null && list.size()>0 && list.get(0)!=null) {
			ServletActionContext.getRequest().getSession().setAttribute("existUser", list.get(0));
			return SUCCESS;
		}
		return LOGIN;
	}

	
	/**
	 * 退出
	 * @return
	 */
	public String exit() {
		ServletActionContext.getRequest().getSession().removeAttribute("existUser");
		return LOGIN;
	}
}
